package study.intconsulting.client;

import javax.swing.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

public class TextViewer extends JFrame implements ActionListener {

	JPanel mainPanel;
	JScrollPane textPanel;
	JTextArea textArea;
	JButton viewButton;
	JFileChooser chooser = new JFileChooser();
	
	final static int WINDOWX = 100;
	final static int WINDOWY = 100;
	final static int WINDOWWIDTH = 800;
	final static int WINDOWHEIGHT = 600;	
	final static int SIDELINESPACE = 8;
	final static float SIDESPACE = 0.9F;
	final static int MENUSPACE = 7;
	final static int VIEWBUTTONWIDTH = 80;
	final static int VIEWBUTTONHEIGHT = 30;
	final static int TEXTAREAX = (int) (WINDOWWIDTH *  ((1 - SIDESPACE)/2) - SIDELINESPACE);
	final static int TEXTAREAY = (int) (WINDOWWIDTH * 0.05);
	final static int TEXTAREAWIDTH = (int) (WINDOWWIDTH * SIDESPACE);
	final static int TEXTAREAHEIGHT = (int) (WINDOWHEIGHT * 0.8);
	final static int VIEWBUTTONX = TEXTAREAX + TEXTAREAWIDTH - VIEWBUTTONWIDTH;
	final static int VIEWBUTTONY = TEXTAREAY + TEXTAREAHEIGHT + MENUSPACE;

	TextViewer() {
		super("Lim Monitor");
		createGUI();			
	}

	public void createGUI() {

		mainPanel = new JPanel();
		mainPanel.setLayout(null);
		textArea = new JTextArea();
		viewButton = new JButton("Open");
		textPanel = new JScrollPane(textArea);
		
		textPanel.setBounds(TEXTAREAX, TEXTAREAY, TEXTAREAWIDTH, TEXTAREAHEIGHT);
		viewButton.setBounds(VIEWBUTTONX, VIEWBUTTONY, VIEWBUTTONWIDTH,
				VIEWBUTTONHEIGHT);

		
		viewButton.addActionListener(this);
		
		mainPanel.add(chooser);
		mainPanel.add(textPanel);
		mainPanel.add(viewButton);

		setBounds(WINDOWX, WINDOWY, WINDOWWIDTH, WINDOWHEIGHT);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setContentPane(mainPanel);
		setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {
		int returnValue = chooser.showOpenDialog(this);
		
		if (returnValue == JFileChooser.APPROVE_OPTION){
			File textFile = chooser.getSelectedFile();
			setTextArea(textFile);
		}
	}
	
	public void setTextArea(File textFile) {

		StringBuffer strBuff = new StringBuffer();
		BufferedReader buff = null;
		String temp = null;

		try {
			
			buff = new BufferedReader(new FileReader(textFile));
			while (true) {
				temp = buff.readLine();
				if (temp == null)
					break;
				strBuff.append(temp + "\n");
			}
			
			buff.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		textArea.setText(strBuff.toString());
		
	}

	public static void main(String[] arguments) {
		new TextViewer();
	}
}
